package icu.feigroup.infrastructure.adapter.port;

import icu.feigroup.domain.trade.adapter.port.ITradePort;
import icu.feigroup.domain.trade.model.entity.NotifyTaskEntity;
import icu.feigroup.infrastructure.gateway.GroupBuyNotifyService;
import icu.feigroup.infrastructure.redis.IRedisService;
import icu.feigroup.types.enums.NotifyTaskHTTPEnumVO;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.redisson.api.RLock;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.util.concurrent.TimeUnit;

/**
 * projectName:icu.feigroup.infrastructure.adapter.port
 *
 * @author 飞
 * @since 2025/2/27 16:32
 * description:
 */
@Slf4j
@Service
public class TradePort implements ITradePort {
    @Resource
    private GroupBuyNotifyService groupBuyNotifyService;
    @Resource
    private IRedisService redisService;
    @Override
    public String groupBuyNotify(NotifyTaskEntity notifyTask) throws Exception {
        RLock lock = redisService.getLock(notifyTask.lockKey());
        try {

            if (lock.tryLock(3,0, TimeUnit.SECONDS)){
                try {
                    if (StringUtils.isBlank(notifyTask.getNotifyUrl())||"暂无".equals(notifyTask.getNotifyUrl())){
                        return NotifyTaskHTTPEnumVO.SUCCESS.getCode();
                    }
                    return groupBuyNotifyService.groupBuyNotify(notifyTask.getNotifyUrl(),notifyTask.getParameterJson());
                }finally {
                    if (lock.isLocked()&&lock.isHeldByCurrentThread()){
                        lock.unlock();
                    }
                }
            }
            return NotifyTaskHTTPEnumVO.NULL.getCode();
        }catch (Exception e){
            Thread.currentThread().interrupt();
            return NotifyTaskHTTPEnumVO.NULL.getCode();
        }
    }
}
